package com.scheduled;

import com.gavel.database.SQLExecutor;
import com.gavel.parser.MYMROSkuParser;
import com.gavel.parser.SkuItem;
import com.gavel.parser.SkuParser;
import com.gavel.utils.StringUtils;
import com.google.gson.Gson;
import com.mrobuy.jdvc.dao.CommonDao;
import com.mrobuy.jdvc.dao.SeachItemDao;
import com.mrobuy.jdvc.entity.*;
import com.mrobuy.jdvc.service.HtmlLodService;
import com.mrobuy.type.ItemState;
import com.mrobuy.util.CodeEncoder;
import com.mrobuy.util.IdentifierGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 上架任务SKU导入
 *
 */
@Component
public class ShelvesItemImportTask {

    private static Logger LOG = LoggerFactory.getLogger(ShelvesItemImportTask.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CommonDao commonDao;

    @Autowired
    private HtmlLodService htmlLodService;

    @Scheduled(fixedRate = 1000*10)
    public void exec() {

        if ( !TaskSwitch.ITEM_IMPORT.get() ) {
            return;
        }

        /**
         *<option value=""> -任务状态- </option>
         * <option value="0">初始</option>
         *<option value="1">等待采集完成</option>
         *<option value="2">商品导入中</option>
         *<option value="3">品牌类目设置</option>
         *<option value="4">商品属性设置</option>
         *<option value="5">等待上架</option>
         *<option value="6">上架中</option>
         *<option value="7">上架完成</option>
         * <option value="8">异常</option>
         */
        List<VCShelvesTask> shelvesTasks = jdbcTemplate.query("select * from VC_SHELVES_TASK  where STATE = ? ", new Object[]{"2"}, new BeanPropertyRowMapper(VCShelvesTask.class));
        if ( shelvesTasks==null || shelvesTasks.size()==0 ) {
            return;
        }

        for (VCShelvesTask shelvesTask : shelvesTasks) {
            try {
                Task task =  (Task) jdbcTemplate.queryForObject("select * from TASK where ID = ? ", new Object[]{shelvesTask.getSource().trim()},  new BeanPropertyRowMapper(Task.class));
                if ( task==null ) {
                    throw  new RuntimeException("[Task: " + shelvesTask.getSource().trim() + "]采集任务未找到.");
                }
                if ( !"success".equalsIgnoreCase(task.getStatus()) ) {
                    shelvesTask.setState("1");
                    commonDao.update(shelvesTask);
                    continue;
                }

                LOG.info("[{}]开始导入SKU信息", shelvesTask.getName());
                try {
                    shelvesItemImport(shelvesTask, task);
                    shelvesTask.setState("3");
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e.getCause());
                    shelvesTask.setState("8");
                    shelvesTask.setRemark(e.getMessage());
                }

                commonDao.update(shelvesTask);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e.getCause());
            }
        }
    }

    private void shelvesItemImport(VCShelvesTask shelvesTask, Task task) {

        List<SearchItem> searchItems = jdbcTemplate.query("select * from SEARCHITEM  where TASKID = ? ", new Object[]{task.getId()}, new BeanPropertyRowMapper(SearchItem.class));
        if ( searchItems==null || searchItems.size()==0 ) {
            return;
        }

        SkuParser skuParser = new MYMROSkuParser();

        for (SearchItem searchItem : searchItems) {
            List<Item> items = new ArrayList<>();
            if ( "u".equalsIgnoreCase(searchItem.getType()) ) {
                Item item = (Item)jdbcTemplate.queryForObject("select * from  ITEM where CODE = ? and TYPE = ? ", new Object[]{searchItem.getCode(), task.getType()}, new BeanPropertyRowMapper(Item.class));
                items.add(item);
            } else if ( "g".equalsIgnoreCase(searchItem.getType()) ) {
                List<Item> _items = jdbcTemplate.query("select * from  ITEM where PRODUCTCODE = ? and TYPE = ? ", new Object[]{searchItem.getCode(), task.getType()}, new BeanPropertyRowMapper(Item.class));
                items.addAll(_items);
            }

            for (Item item : items) {

                String code = StringUtils.trim(task.getType()) + "-" + StringUtils.trim(item.getCode());

                VCShelvesItem shelvesItem = new VCShelvesItem();
                try {
                    VCShelvesItem exist = (VCShelvesItem) jdbcTemplate.queryForObject("select * from  VC_SHELVES_ITEM where TASKID = ? and CODE = ?", new Object[]{shelvesTask.getId(), code}, new BeanPropertyRowMapper(VCShelvesItem.class));
                    if ( exist!=null ) {
                        shelvesItem.setId(exist.getId());
                    }
                } catch (EmptyResultDataAccessException e) {

                } catch (Exception e) {
                    LOG.error(e.getMessage(), e.getCause());
                }

                String html = htmlLodService.load(item.getUrl());

                SkuItem skuItem = skuParser.parser(item.getUrl(), html);

                LOG.info("[导入]{} - {}", item.getCode(), item.getName());
                shelvesItem.setTaskid(shelvesTask.getId());
                shelvesItem.setCode(code);
                shelvesItem.setProductcode(item.getProductcode());
                shelvesItem.setProductname(item.getProductname());

                String productname = item.getProductname().replace("，", " ");
                if (  StringUtils.isNotBlank(skuItem.getBrand()) ) {
                    productname = StringUtils.replaceIgnoreCase(productname, skuItem.getBrand(), "");
                }
                if (  StringUtils.isNotBlank(skuItem.getBrandEn()) ) {
                    productname = StringUtils.replaceIgnoreCase(productname, skuItem.getBrandEn(), "");
                }
                shelvesItem.setJdproductname(productname);

                shelvesItem.setSkucode(item.getCode());
                shelvesItem.setSkuname(item.getName());

                String skuname = item.getName().replace("，", " ");
                if (  StringUtils.isNotBlank(skuItem.getBrand()) ) {
                    skuname = StringUtils.replaceIgnoreCase(skuname, skuItem.getBrand(), "");
                }
                if (  StringUtils.isNotBlank(skuItem.getBrandEn()) ) {
                    skuname = StringUtils.replaceIgnoreCase(skuname, skuItem.getBrandEn(), "");
                }
                shelvesItem.setJdskuname(skuname);

                shelvesItem.setModel(skuItem.getModel());
                shelvesItem.setUnit(skuItem.getUnit());
                shelvesItem.setDeliverydate(skuItem.getFahuori());

                Map<String, String> attrs = skuItem.getAttrs();
                if ( attrs==null ) {
                    attrs = new HashMap<>();
                }
                attrs.remove("制造商型号");
                attrs.remove("包装数量");
                shelvesItem.setAttrs(new Gson().toJson(attrs));

                shelvesItem.setZt(ItemState.INIT.code());
                shelvesItem.setType(task.getType());

                shelvesItem.setBrand(skuItem.getBrand());
                shelvesItem.setBranden(skuItem.getBrandEn());
                if ( skuItem.getCategories().size() >=1  ) {
                    shelvesItem.setCate1(skuItem.getCategories().get(0));
                }
                if ( skuItem.getCategories().size() >=2  ) {
                    shelvesItem.setCate2(skuItem.getCategories().get(1));
                }
                if ( skuItem.getCategories().size() >=3  ) {
                    shelvesItem.setCate3(skuItem.getCategories().get(2));
                }
                if ( skuItem.getCategories().size() >=4  ) {
                    shelvesItem.setCate4(skuItem.getCategories().get(3));
                }

                shelvesItem.setItemNum(CodeEncoder.encode(skuItem.getCode(), Math.abs(item.getProductcode().hashCode()%9) + 1));

                // 计算价格
                int newScale = 1;
                float price = skuItem.getOriginalPrice();
                if ( price > 50 ) {
                    newScale = 0;
                }
                BigDecimal purchasePrice = new BigDecimal(price * 1.05 ).setScale(newScale, RoundingMode.HALF_DOWN);
                BigDecimal memberPrice = purchasePrice.multiply(new BigDecimal(1.17)).setScale(newScale, RoundingMode.HALF_DOWN);;
                BigDecimal marketPrice = new BigDecimal(price * 1.38).setScale(newScale, RoundingMode.HALF_DOWN);

                shelvesItem.setPrice(String.valueOf(price));

                shelvesItem.setMarketPrice(marketPrice.stripTrailingZeros().toPlainString());
                shelvesItem.setPurchasePrice(purchasePrice.stripTrailingZeros().toPlainString());
                shelvesItem.setMemberPrice(memberPrice.stripTrailingZeros().toPlainString());

                if (StringUtils.isBlank(shelvesItem.getId())) {
                    shelvesItem.setId(IdentifierGen.uuid());
                    shelvesItem.setEnable("N");
                    commonDao.insert(shelvesItem);
                } else {
                    commonDao.update(shelvesItem, false);
                }

            }
        }


    }

}
